package com.anosine.gpsl.android.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * @Title: StringUtil
 * @Package com.anosine.gpsl.android.util
 * @Description: String的一些操作
 * @author: sunny
 * @date: 2015-11-19
 * @version V1.0
 */
public class StringUtil {
	/**
	 * will trim the string
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s) {
		if (null == s)
			return true;
		if (s.length() == 0)
			return true;
		if (s.trim().length() == 0)
			return true;
		return false;
	}

	public static String emptyStringIfNull(String s) {
		return (null == s) ? "" : s;
	}

	public static String humanReadableByteCount(long bytes) {
		int unit = 1024;
		if (bytes < unit)
			return bytes + " B";
		int exp = (int) (Math.log(bytes) / Math.log(unit));
		String pre = "KMGTPE".charAt(exp - 1) + "";
		return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
	}

	public static String fixedLengthString(String s, int expectedLength) {
		int l = s.length();
		if (l >= expectedLength) {
			return s;
			// return s.substring(0, expectedLength);
		}
		for (int i = 0; i < expectedLength - l; i++) {
			s = s + " ";
		}
		return s;
	}

	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	public static String toMD5(String source) {
		if (null == source || "".equals(source))
			return null;
		try {
			MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(source.getBytes());
			return toHex(digest.digest());
		} catch (NoSuchAlgorithmException e) {
		}
		return null;
	}

	public static String toHex(byte[] buf) {
		if (buf == null)
			return "";
		StringBuffer result = new StringBuffer(2 * buf.length);
		for (int i = 0; i < buf.length; i++) {
			appendHex(result, buf[i]);
		}
		return result.toString();
	}

	private final static String HEX = "0123456789ABCDEF";

	private static void appendHex(StringBuffer sb, byte b) {
		sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
	}
	public static boolean isEmptyOrNull(String str) {
		return str == null || str.trim().length() <= 0
				|| str.trim().toLowerCase().equals("null")
				|| str.trim().equals("");
	}

	public static boolean isEmptyOrZero(String str) {
		return isEmptyOrNull(str) || "0".equals(str);
	}

	public static boolean isNotEmpty(String str) {
		return !isEmptyOrNull(str);
	}
}
